<?php
/**
 * 
 */
class gRequest extends gCoreObject
{
    const REQ_GET = 'get';
    const REQ_POST = 'post';
    const REQ_PUT  = 'put';
    const REQ_DELETE = 'delete';
    const REQ_HEAD = 'head';
    const REQ_OPTIONS = 'options';
	
    protected $_baseUrl = null;
    protected static $_url  = null;
    protected static $_rawBody = null;
    
    protected static $_call = array(
        'controller' => 'content',
        'action'     => 'index',
        'params'     => null,
        'subdomain'  => null,
        'hostUrl'    => null
    );
    
    protected static $_params = array();
    

    protected $_responseHeaders = array();
    
    public function init()
    {
        self::$_url = $_SERVER['REQUEST_URI'];
    }
    /**
     * @desc Return http request method
     * @return
     */
    public static function getMethod()
    {
        if( !array_key_exists('REQUEST_METHOD', $_SERVER))
        {
            throw new gException('Cannot detect http request type',  gError::CORE);
        }
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        return $method;
    }
    /**
     * @desc Checks whether parameter exists in GET or POST data
     * @param string $name
     */
    public static function hasParam()
    {
    	$args = func_get_args();
    	
		if( func_num_args() > 1){
			$result = true;
			foreach( $args as $key=>$val ){
				if( !array_key_exists($key,self::$_params)) $result = false;
			}
			return $result;
		} else if ( func_num_args() ==1 ) {
			return array_key_exists($args[0],self::$_params);
		}
		else return false;
    }
        
    public static function getCall()
    {
    	return self::$_call;
    }
    

    public static function getController()
    {
        return self::$_call['controller'];
    }

    public static function getAction()
    {
        return self::$_call['action'];
    }

    public static function getHostUrl()
    {
        return self::$_call['baseUrl'];
    }

    /**
     * @desc Parses request parameters
     * @return bool
     */
    public static function parseRequest()
    {
        $url = str_replace(gApp::get('url'),'',self::$_url);
        $pattern = '/^\/?([A-z0-9-_]{1,20})\/?([A-z0-9-_]+)?\/?\??(.{1,100})?/is';
        if( preg_match($pattern,$url,$result))
        {
            // if just alias - content
            if( count($result) <= 2)
            {
                $dir = gApp::getModPath($result[1]);
                if( is_dir($dir))
                {
                    self::$_call['controller'] = $result[1];
                    self::$_call['action']     = 'index';
                }
                else
                {
                    self::$_call['controller'] = 'content';
                }
                return;
            }
            self::$_call['controller'] = $result[1];
            self::$_call['action']     = $result[2];
            self::$_call['params']     = isset($result[3]) ? $result[3] : array();
            self::$_call['domain']     = $_SERVER['SERVER_NAME'];
            self::$_call['hostUrl']    = isset($_SERVER['HTTPS']) ? 'https://' : 'http://' . self::$_call['domain'];
        }
        self::getParams();
    }
	
    /**
     * @desc Returns requested content type
     * @return string
     */
    public function getContentType()
    {
        $headers = get_headers('');
        return $headers['Content-Type'];
    }

    /*
     * Response handling area
     */

    public function setContentType($type)
    {
        header('Content-type: ' . $type);
    }

    public function setCookie($name, $value = '', $expire = 0, $path = null, $domain = null, $secure = false, $httponly = false)
    {
        setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
    }

    public function sendHeaders()
    {
        
    }
    
    public static function getRawBody()
    {
    	if( self::$_rawBody == null){
    		$body = file_get_contents('php://input');
    		if( strlen(trim($body))){
    			self::$_rawBody = $body;
    		} else {
    			self::$_rawBody = false;
    		}
    	}
    	return self::$_rawBody;
    }
    /*
     * 
     */
    public static function & getParams()
    {
    	if( count(self::$_params) == 0) {
	    	$data = array();
	    	if( self::getMethod()!= self::REQ_GET && self::getMethod() != self::REQ_POST ){
	    		$data =array();
	    		parse_str(self::getRawBody(),$data);
	    	}
	    	self::$_params = array_merge($_GET,$_POST,$data);
	    	self::$_params['controller'] = self::getController();
	    	self::$_params['action'] = self::getAction();
    	}
    	return self::$_params;
    }
    /**
     * 
     * Enter description here ...
     * @param unknown_type $name
     * @return value or null
     */
    public static function getParam($name)
    {
    	return array_key_exists($name,self::$_params) ? self::$_params[$name] : null;
    }
    
    public function getUrl()
    {
    	return self::$_url;
    }
}